package com.ruoyi.system.controller;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.RxDoudianMsg;
import com.ruoyi.system.mapper.RxDoudianMsgMapper;
import com.ruoyi.system.utils.IPCheck;
import com.ruoyi.system.utils.JsonToPhp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.security.PermitAll;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Slf4j
@RestController
@RequestMapping("/hmk/douDianCallBack/")
public class DouDianCallBackController {


    @Autowired
    private RxDoudianMsgMapper rxDoudianMsgMapper;


    @PermitAll
    @PostMapping("/helloWorld")
    public Map<String, Object> helloWorld(@RequestBody List<Map<String, Object>> requestBodyList) {
        log.info("/hmk/douDianCallBack/helloWorld被触发");
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "success");
        if (requestBodyList != null && !requestBodyList.isEmpty()) {
            Map<String, Object> firstItem = requestBodyList.get(0);
            String tag = (String) firstItem.get("tag");
            String msgId = (String) firstItem.get("msgId");
            String data = (String) firstItem.get("data");
            log.info("Received - tag: {}, msgId: {}, data: {}", tag, msgId, data);
            if (!IPCheck.checkIp()) {
                return map;
            }
            if (StringUtils.isNotEmpty(tag) && StringUtils.isNotEmpty(data) && (!"0".equals(tag))) {
                String phpDataStr = JsonToPhp.jsonStrToPhpHead(data);
                log.info("准备插入rx_doudian_msg_2表,转php格式:{}", phpDataStr);
                RxDoudianMsg rxDoudianMsg = new RxDoudianMsg();
                rxDoudianMsg.setTag(tag);
                rxDoudianMsg.setMsgId(msgId);
                rxDoudianMsg.setData(phpDataStr);
                rxDoudianMsg.setStatus(1);
                rxDoudianMsg.setTime(System.currentTimeMillis() / 1000);
                rxDoudianMsg.setCreateTime(new Date(rxDoudianMsg.getTime() * 1000L));
                rxDoudianMsgMapper.insertRxDoudianMsg(rxDoudianMsg);
            }
        }
        return map;
    }


}
